package org.king;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.king.config.MainConfiguration;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.io.IOException;

public class MainApplication extends Application {
    private static ConfigurableApplicationContext springContext; // 改用 ConfigurableApplicationContext
    private static Stage stage;

    @Override
    public void init() {
        springContext = new AnnotationConfigApplicationContext(MainConfiguration.class);
    }

    @Override
    public void start(Stage stage) throws IOException {
        MainApplication.stage = stage;
        stage.setTitle("活动数据库管理系统");
        changeView("/view/auth/login-view.fxml");
        stage.show();
    }

    public static void changeView(String fxml) {
        try {
            FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource(fxml));
            // 关键：让 Spring 管理 Controller 的创建和依赖注入
            loader.setControllerFactory(springContext::getBean);

            Parent root = loader.load();
            stage.setScene(new Scene(root));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        springContext.close(); // 关闭 Spring 上下文
    }

    public static void main(String[] args) {
        launch(args);
    }
}